/*
 * Creater:     柿子
 * CreateDate:  2022/04/21
 * Describe：   弹窗表单公共组件
 * */
import React, { Component } from 'react';
import { Modal, Button } from 'antd';
import DynamicRenderingForm from './DynamicRenderingForm';
class PublicModalFormHooks extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      isUpload: false
    };
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 修改弹窗状态
  modifyVisible = (visible, isReset) => {
    if (isReset === 'Y') {
      this.formRef && this.formRef.resetFields();
    }
    this.setState({ visible }, () => {
      if (this.state.visible && !this.state.isUpload) {
        setTimeout(() => {
          this.setState({ isUpload: true });
          this.formRef && this.formRef.handleDefaultAssignment();
        }, 0)
      }
    })
  }

  // 获取数据
  getFieldsValue = () => {
    let fromValues = this.formRef && this.formRef.getFieldsValue();
    return {
      ...fromValues,
    }
  }

  // 设置表单数据
  setFieldsValue = values => {
    this.formRef && this.formRef.setFieldsValue(values);
  }

  // 重置
  resetFields = () => {
    this.formRef && this.formRef.resetFields();
  }

  // 保存
  handleSave = () => {
    this.formRef && this.formRef.handleSave().then(result => {
      if (!result?.error) {
        this.props.handleSave && this.props.handleSave(result)
      }
    });
  }

  // 关闭弹窗
  handleCancel = () => {
    let fieldsValue = this.getFieldsValue(); // 关闭弹窗的时候记录表单输入的值
    this.props.recordFormInput && this.props.recordFormInput(fieldsValue);
    this.modifyVisible(false);
  }

  render() {
    let { title, isFooter, idField, width, formItemCol, formData, selectData, rowData } = this.props;
    let { visible } = this.state;
    return (
      <Modal
        visible={visible}
        width={width || '800px'}
        maskClosable={'maskClosable' in this.props ? this.props.maskClosable : true}
        title={title ? title : ((rowData && ((idField && rowData[idField]) || ('id' in rowData && rowData.id))) ? '编辑' : '新增')}
        footer={isFooter !== 'N' ? (
          <div>
            <Button onClick={this.handleCancel}>{(rowData && ((idField && rowData[idField]) || ('id' in rowData && rowData.id))) ? '取消修改' : '取消'}</Button>
            <Button type="primary" onClick={this.handleSave}>{(rowData && ((idField && rowData[idField]) || ('id' in rowData && rowData.id))) ? '确认修改' : '保存'}</Button>
          </div>
        ) : null}
        onCancel={this.handleCancel}
      >
        <DynamicRenderingForm
          rowData={rowData || {}}
          formData={formData || {}}
          selectData={selectData || {}}
          formItemCol={formItemCol ? formItemCol : { labelCol: 8, wrapperCol: 16 }}
          onRef={ref => this.formRef = ref}
        />
      </Modal>
    )
  }
};

export default PublicModalFormHooks;